var gridNum = 32;       //格子数目
var GRID_WIDTH = isMobile()?$("#gridCon").outerWidth():$("#gridCon").outerHeight();  //总大小
const BORDER_WIDTH = 1; //格子边框

window.onresize = function(){
    setGRID_WIDTH();
    createGrids(gridNum);   
    styleJust(); 
}

window.onload = function () { 
    setGRID_WIDTH();
    createGrids(gridNum);   
    styleJust(); 
    this.initFileList();
    //绘图函数
    $('#gridCon').on('click','.grid',function () {
        if (this.style.backgroundColor === '') {
            this.style.backgroundColor = "#"+$('#valueInput').val();
        }else{
            this.style.backgroundColor = '';
        }
    });

    $('grid').hover(function () {
            // over
            $(this).css({
            'z-index': 2,
            'borderWidth': '1px',
            'box-shadow': '0 0 3px 1px #fff, 0 0 10px 10px burlywood'
        });
        }, function () {
            // out
            $(this).css({
            'z-index': 1,
            'background-color':'',
            'borderWidth': '1px',
            'box-shadow': ''
        });
        }
    );

    //选择格子数量
    $('.gridSelect').click(function () { 
        let temp = $(this).text();
        let num =  $(this).attr('value');
        $('#showGridNum').text(temp);
        gridNum = parseInt(num);
        createGrids(gridNum);
        styleJust();
    })
    //加载点击文件
    $('#fileList').on('click','.list-group-item',function(){
        let fileName = $(this).find("span.filename").text();
        let filetype = $(this).attr('type');
        // console.log(filetype);
        // console.log(fileName);
        let type = getFileType(fileName);
        if (parseInt(type) === gridNum) {
            cleanColor();
            filetype=="online"?loadFile(fileName):loadLocalFile(fileName); 
        }else{
            alert('该文件与当前表格不符！')
        }   
    });
    //删除本地文件
    $('#fileList').on('click','.delLocalFileBtn',function(e){
        let thisFile = $(this).parents(".list-group-item");
        let filename = thisFile.find("span.filename").text();
        console.log(filename);
        e.stopPropagation();
        $('.delBtn').on('click',function(){
            thisFile.remove();
            deleteLocalFile(filename);  
        });
    });
    //一键清屏
    $('#cleanBtn').click(function () {
        console.log('clean');
        cleanColor(); 
    });
    
    // 保存文件
    $('#saveBtn').click(function(){
        let tempArr = getColor();
        let tempStr = arrayStr(tempArr);
        let tempName =  $('#fileName').val();
        let filename = tempName === ''?getTime():tempName;
        filename = filename + '_' + gridNum;
        addLocalFile(filename);
        $('#fileName').val('');
        // console.log(tempStr);
        var obj = {"filename":filename,"type":gridNum,"content": tempStr};
        obj = JSON.stringify(obj); //转化为JSON字符串
        localStorage.setItem(getTime(), obj);
        // xtip.msg(filename+'已保存！');
    });

    //弹出框
    $('[data-toggle="tooltip"]').tooltip();
    $('[data-toggle="delConfirm"]').popover({
        placement : 'left',
        container : 'body',
        html : true,
        title : '<b class="text-danger">警告<b/>',
        trigger: "focus",
        content : `<div>
            <p>删除后不可恢复！继续删除？</p>
            <div class="btn-group btn-group-justified" role="group">
              <a class="btn btn-danger delBtn">确认</a>
              <a class="btn btn-default cancelBtn">取消</a>
            </div>
        </div>`
    });

    // 整体移动
    $('.blockMove').on('click', function () {
        // console.log($(this).attr('value'));
        blockMove($(this).attr('value'),1);
    });

    //打开画笔
    $('#penBtn').on('click',function () { 
        let flag = $('#penBtn').hasClass('active');
        if (flag) {
            $('#penBtn').removeClass('active');
        } else{
            $('#penBtn').addClass('active');
            onCrayon();
        }
    });

}

function confirmDel(){
    CANDELETE = true;

}
/**
 *布局样式微调
 *
 */
function styleJust() {
    if (!isMobile()) {
        $("#gridCon").css("padding",($("#gridCon").outerHeight()-$(".grid").outerWidth()*gridNum -2)/2 +"px "+ ($("#gridCon").outerWidth()-$(".grid").outerWidth()*gridNum -2)/2 + "px");
    } else {
        $("#gridCon").css("padding",($("#gridCon").outerHeight()-$(".grid").outerWidth()*gridNum -2)/2 + "px");    
    }
    $('#rightCon').css('height',$('#leftCon').css('height')); 
    $('#fileList').css('height',parseFloat($('#leftCon').css('height'))-parseFloat($('#fileCon').css('height'))-parseFloat($('p.text-primary').css('height'))-23);    
}

/**
 *
 *
 * @param {*格子宽度} width
 * @param {*格子边框宽带} border
 * @param {*格子id} id
 * @returns
 */
function createOneGrid(width,border,id) {
    let grid = document.createElement('div');
    grid.style.position = 'relative';
    grid.style.width = width + 'px';
    grid.style.height = width + 'px';
    grid.style.backgroundColor = 'rgb(255, 255, 255)';
    grid.style.border = border + 'px';
    grid.style.borderColor = 'rgb(191, 162, 119)';
    grid.style.borderStyle = 'solid';
    grid.style.float = 'left';
    grid.style.cursor = 'crosshair';
    grid.style.transition = 'box-shadow 0.3s';
    grid.className = 'grid';
    grid.id = id;
    return grid;
}


/**
 *创建所有指定是数量格子
 *
 * @param {*格子数量} gridNum
 */
function createGrids(gridNum){
    $('#gridCon').empty();
    let gridWidth = Math.floor(GRID_WIDTH/gridNum);
    let gridCon = $('#gridCon')[0];//棋盘对象
    for (let i = 0; i < gridNum; i++) {
        for (let j = 0; j < gridNum; j++) {
            gridCon.append(createOneGrid(gridWidth,BORDER_WIDTH,i+'_'+j));
        }
    }
    for (let i = 0; i < gridNum; i++) {
        let flag = gridNum/2;
        $('#'+i+'_'+flag).css('borderLeft','1px solid black')
        $('#'+flag+'_'+i).css('borderTop','1px solid black')     
    }
    //$('#0_0').addClass('selected');
}



/**
 *设置格子颜色
 *
 * @param {*格子颜色数组} colorArr
 */
function setColor(colorArr) {
    for (let i = 0; i < colorArr.length; i++) {
        $('#'+colorArr[i].split('%')[0]).css('background-color',colorArr[i].split('%')[1]);
    }
}



/**
 *一键清除格子颜色
 *
 */
function cleanColor() {
    for (let i = 0; i < gridNum; i++) {
        for (let j = 0; j < gridNum; j++) {
            $('#'+i+'_'+j).css('background-color','rgb(255, 255, 255)');         
        }
    }
}

/**
 *获取所有格子颜色信息
 *
 */
function getColor() {
    let colorArr = [];
    for (let i = 0; i < gridNum; i++) {
        for (let j = 0; j < gridNum; j++) {
            let color = $('#'+i+'_'+j).css('background-color');
            if (color == "rgba(0, 0, 0, 0)" || color == "rgb(255, 255, 255)") {
                continue;
            }
            colorArr.push(i+'_'+j+'%'+$('#'+i+'_'+j).css('background-color'));         
        }
    }
    return colorArr;
}


/**
 *整理数组成字符串
 *
 * @param {*} params
 */
function arrayStr(colorArr) {
    var msg = '';
    for (let i = 0; i < colorArr.length; i++) {
        msg += colorArr[i]+'@';
    }
    return msg;
}



/**
 *字符串还原数组
 *
 * @param {*} str
 */
function strArray(str) {
    var newstr = str.split('@');
    var arr =[];
    for (let i = 0; i < newstr.length-1; i++) {
        arr.push(newstr[i]);
    }
    return arr;
}


/**
 *获取当前时间
 *"2020-02-18 13:3:31"
 * @
 */
function getTime() {
    var date = new Date();
    Y = date.getFullYear() + '-';
    M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
    D = date.getDate() < 10 ? '0'+date.getDate() : date.getDate() + ' ';
    h = date.getHours() < 10 ? '0'+date.getHours() + '-': date.getHours() + '-';
    m = date.getMinutes() < 10 ? '0'+date.getMinutes() + '-': date.getMinutes() + '-';
    s = date.getSeconds() < 10 ? '0'+date.getSeconds() : date.getSeconds();
    //console.log(Y+M+D+h+m+s);
    return Y+M+D+h+m+s;
}

/**
 * 初始化格子总大小
 */
 function setGRID_WIDTH(){
    if (isMobile()) {
        GRID_WIDTH = $("#gridCon").outerWidth();
    }else{
        GRID_WIDTH = $("#gridCon").outerWidth()<$("#gridCon").outerHeight()?$("#gridCon").outerWidth():$("#gridCon").outerHeight();  //总大小
    }
}

/**
 *判断是否移动端
 * @
 */
function isMobile()
{
    var sUserAgent = navigator.userAgent.toLowerCase();  //返回由客户机发送服务器的user-agent 头部的值
    var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";   
    //JavaScript match() 方法在字符串内检索指定的值，或找到1 or N个正则表达式的匹配。返回被检所的值或“null”
    var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";   
    var bIsMidp = sUserAgent.match(/midp/i) == "midp";   
    var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";  
    var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";   
    var bIsAndroid = sUserAgent.match(/android/i) == "android";   
    var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";  
    var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";  
    if(bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {
        console.log("is mobile");
        return true;
    }
    return false;
}

/**
 *获取服务端存在的所有文件名称
 *用于初始化
 * @param {*服务端返回的文件名列表} obj
 */
function addFile(obj,filetype) {
    for (let i = 0; i < obj.length; i++) {
        let filename = obj[i].name;  
        let type = obj[i].type;
        var grid = document.createElement('div');
        grid.className = 'btn list-group-item gridNum_'+type;
        grid.setAttribute('type',filetype);
        let content = `
        <i class="filelogo `+filetype+`"></i>
        <span class="filename">`+filename+`</span>
        `;
        if (filetype=="offline") {
            content += `
            
            <button class="btn btn-danger btn-xs delLocalFileBtn" data-toggle="delConfirm">删除</button>`;
        }
        /*<button class="btn btn-link btn-xs uploadbtn">上传</button>*/
        grid.innerHTML = content;
        $('#fileList').append(grid);
    }
}


/**
 *获取该文件所属表格类型
 *24 36 48
 * @param {*文件名称} fileName
 * @returns
 */
function getFileType (fileName) {  
    let type = fileName.substring(fileName.length-2);
    return type;
}

/**
 *保存文件名称在本地
 *
 * @param {*文件名称} filename
 */
function addLocalFile(filename){
    // 24  223, 240, 216
    //36 217, 237, 247
    //48 242, 222, 222
    let type = getFileType(filename);
    var grid = document.createElement('div');
    grid.className = 'btn list-group-item gridNum_'+type;
    grid.setAttribute('type','offline');
    let content = `
    <i class="filelogo offline"></i>
    <span class="filename">`+filename+`</span>
    
    <button class="btn btn-danger btn-xs delLocalFileBtn" data-toggle="delConfirm">删除</button>
    `;
    /*<button class="btn btn-link btn-xs uploadbtn">上传</button>*/
    grid.innerHTML = content;
    $('#fileList').append(grid);
    $('[data-toggle="delConfirm"]').popover({
        placement : 'left',
        container : 'body',
        html : true,
        title : '<b class="text-danger">警告<b/>',
        trigger: "focus",
        content : `<div>
            <p>删除后不可恢复！继续删除？</p>
            <div class="btn-group btn-group-justified" role="group">
              <a class="btn btn-danger delBtn">确认</a>
              <a class="btn btn-default cancelBtn">取消</a>
            </div>
        </div>`
    });
}


/**
 *向服务端请求文件
 *
 * @param {*请求的文件名称} filename
 * @returns
 */
function loadFile(filename) {  
    var url = "./public/files/"+filename +".gd";
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);   // 也可以使用POST方式，根据接口
    xhr.responseType = "blob";    // 返回类型blob
    // 定义请求完成的处理函数，请求前也可以增加加载框/禁用下载按钮逻辑
    xhr.onload = function () {
        // 请求完成
        if (this.status === 200) {
            // 返回200
            let blob = this.response;
            let reader = new FileReader();
            reader.readAsText(blob,"utf-8");
            reader.onload = function (e) {
                // console.log(e.target.result)
                let colorArr = strArray(e.target.result);
                // console.log('colorArr',colorArr);
                setColor(colorArr);
            }
        }
    };
    // 发送ajax请求
    xhr.send()
}

/**
 * 加载本地文件
 */
function loadLocalFile(filename){
    var colorArr = [];
    for(var i = 0; i < localStorage.length; i++){
        if(localStorage.key(i).length!=19)
        {
            continue;
        }
        var cur = localStorage.getItem(localStorage.key(i));
        var obj = JSON.parse(cur);
        if (obj.filename!=filename) {
            continue;
        }
        colorArr = strArray(obj.content);
    }
    setColor(colorArr);
}

/**
 * 删除本地文件
 */
 function deleteLocalFile(filename){
    for(var i = 0; i < localStorage.length; i++){
        if(localStorage.key(i).length!=19)
        {
            continue;
        }
        var cur = localStorage.getItem(localStorage.key(i));
        var obj = JSON.parse(cur);
        if (obj.filename!=filename) {
            continue;
        }
        localStorage.removeItem(localStorage.key(i));
        console.log(filename+'已删除');
    }
}

/**
 *初始化文件列表
 *
 */
function initFileList() {
    $('#fileList').empty();
    //获取本地文件列表
    var localFileName = [];
    for(var i = 0; i < localStorage.length; i++){
        if(localStorage.key(i).length!=19)
        {
            continue;
        }
        var cur = localStorage.getItem(localStorage.key(i));
        var obj = JSON.parse(cur);
        localFileName.push({"name":obj.filename,"type":obj.type});
    }
    // console.log(localFileName);
    if (localFileName.length>0) {
        addFile(localFileName,"offline");
    }

    //获取在线文件列表
    var url = './public/files/list.json';
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);   // 也可以使用POST方式，根据接口
    xhr.responseType = "blob";    // 返回类型blob
    // 定义请求完成的处理函数，请求前也可以增加加载框/禁用下载按钮逻辑
    xhr.onload = function () {
        // 请求完成
        if (this.status === 200) {
            // 返回200
            let blob = this.response;
            let reader = new FileReader();
            reader.readAsText(blob,"utf-8");
            reader.onload = function (e) {
                addFile(eval(e.target.result),"online");
            }
        }
    };
    // 发送ajax请求
    xhr.send();
}


/**
 *图案整体移动
 *
 * @param {*移动方向} dir
 * @param {*移动长度个数} num
 */
function blockMove(dir,num) {
    if (num >= gridNum) {
        alert('移动数量严重超出范围！');
        return;
    }
    var colorArr = getColor();
    var newColorArr = [];      
    cleanColor();
    switch (dir) {
        case 'up':
            for (let i = 0; i < colorArr.length; i++) {
                let grid = colorArr[i].split('%')[0];
                let color = colorArr[i].split('%')[1];
                let x = parseInt(grid.split('_')[0]);
                let y = parseInt(grid.split('_')[1]);
                newColorArr.push(x-num+'_'+y+'%'+color);
            }
            break;
        case 'down':
            for (let i = 0; i < colorArr.length; i++) {
                let grid = colorArr[i].split('%')[0];
                let color = colorArr[i].split('%')[1];
                let x = parseInt(grid.split('_')[0]);
                let y = parseInt(grid.split('_')[1]);
                newColorArr.push(x+num+'_'+y+'%'+color);
            }
            break;
        case 'left':
            for (let i = 0; i < colorArr.length; i++) {
                let grid = colorArr[i].split('%')[0];
                let color = colorArr[i].split('%')[1];
                let x = parseInt(grid.split('_')[0]);
                let y = parseInt(grid.split('_')[1]);
                newColorArr.push(x+'_'+(y-num)+'%'+color);
            }
            break;
        case 'right':
            for (let i = 0; i < colorArr.length; i++) {
                let grid = colorArr[i].split('%')[0];
                let color = colorArr[i].split('%')[1];
                let x = parseInt(grid.split('_')[0]);
                let y = parseInt(grid.split('_')[1]);
                newColorArr.push(x+'_'+(y+num)+'%'+color);
            }
            break;
        default:
            break;
    }        
    setColor(newColorArr);
}



/**
 *画笔功能
 *点击画笔按钮后，按下鼠标移动即可上色
 * 
 * @returns
 */
function onCrayon() {
    let isPen = $('#penBtn').hasClass('active');
    let drawing = false;
    console.log('isPen',isPen);
    var deviceAgent = navigator.userAgent.toLowerCase();

    if (!isPen) {
        return;
    } else {
        if (deviceAgent.indexOf('mobile') > -1 ||deviceAgent.indexOf('android') > -1 || deviceAgent.indexOf('iphone') > -1 || deviceAgent.indexOf('ipad') > -1 || deviceAgent.indexOf('ipod') > -1 || deviceAgent.indexOf('symbian') > -1) {
            $('.grid').on('touchstart',function () {
                drawing = true;
                // console.log($(this));
            }).on('touchmove',function(e){
                $(this).css('background-color',"#"+$('#valueInput').val())
                var myLocation = e.originalEvent.changedTouches[0];
                var realTarget = document.elementFromPoint(myLocation.clientX, myLocation.clientY);  
                if (drawing) {
                    realTarget.style.backgroundColor = "#"+$('#valueInput').val();
                    // console.log(myLocation);
                    // console.log(realTarget);
                }
            }).on('touchend',function () {  
                drawing = false;
            });
            // console.log('phone');
        } else {
            $('.grid').on('mousedown',function () {
                drawing = true;
            }).on('mousemove',function(){
                if (drawing) {
                    // console.log();
                    $(this).css('background-color',"#"+$('#valueInput').val())
                }
            }).on('mouseup',function () {  
                drawing = false;
            });
            // console.log('pc');
        }
    }
}   